/**
 * author:Administrator
 * date:2015/7/27
 * desc:TODO
 */
'use strict';

// real-time topic of interested

var model = require('../../model/mongo/rtToi.js');
let fout = require('../../common/function.js').formatOutput;

function MongoDao() {
    let self = this instanceof MongoDao ? this : new MongoDao();
    return self;
}
module.exports = MongoDao;
var theProto = MongoDao.prototype;

// theProto.saveOne = function*(json) {
// 	let uid = json.uid;
// 	let newTags = json.tags;
// 	let oldTags = [];


// 	// find if exist
// 	let doc = yield model.findOne({
// 		uid: json.uid
// 	});
// 	if (doc) {
// 		console.log('find');
// 		oldTags = doc.tags;
// 	}
// 	let savedTags = __getSavedTags(newTags, oldTags);

// 	let result = yield model.upsert({uid:uid},{tags:savedTags});
// 	return result;
// };

theProto.saveOne2 = function (json) {
    //console.log('MongoDao.theProto.addOne2');
    let uid = json.uid;
    let newTags = json.tags;
    //console.log(newTags);

    return model.findOne({
        uid: json.uid
    }).then(function (doc) {
        let oldTags = [];
        if (doc) {
            console.log('findOne fulfil:uid find');
            oldTags = doc.tags;
        } else {
            console.log('findOne fulfil:uid not find');
        }

        let savedTags = __getSavedTags(newTags, oldTags);
        //console.log('__savedTags', savedTags);

        if (!doc) {
            return new model({uid: uid, tags: savedTags}).save();
        } else {
            // update
            return model.findOneAndUpdate({uid: uid}, {$set: {tags: savedTags, updatedAt: new Date()}});
        }

    }, function (err) {
        console.log('findOne reject');
    });
};

// savedTags = f(newTags, oldTags), for current, simple +1 score
function __getSavedTags(newTags, oldTags) {
    let result = [];
    for (let i = 0; i < oldTags.length; i++) {
        let item = oldTags[i];
        let tag = item.tag;
        let index = newTags.indexOf(tag);
        if (index >= 0) {
            newTags.splice(index, 1);
            item.value++;
        }
        result.push(item);
    }

    for (let i = 0; i < newTags.length; i++) {
        result.push({
            tag: newTags[i],
            value: 1
        });
    }

    return result;
}

// theProto.getByUid = function*(uid) {
// 	let query = {
// 		uid: uid
// 	};
// 	let result = yield model.findOne(query);
// 	return result && result._doc;
// };